package Android.SinYateClient;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class AndroidClient extends Activity {
	private static final int STOP = 1;
	private WebView wv;
	private Timer t;
	private int aantImages;
	private int delay;
	private int interval;
	private int count;
	private String url;
	private boolean doeScreenshotTask = false;
	private ClientDriver cd;
	private Task appTask;
	private Task screenshotTask;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browser);
		setTitle("SinYateClient");

		// String ip = "192.168.0.3";
		String ip = "10.10.129.20";

		// klasse die DeviceEigen info ophaalt
		DeviceInfo di = new DeviceInfo(this);
		// System.out.println("ip: " + di.getIpAdres());

		cd = new ClientDriver(ip, "8080", 3, di.getIpAdres(), "0", this);

		Timer tim = new Timer();

		tim.scheduleAtFixedRate(new executeTask(), 1000, 1000);
	}

	private class executeTask extends TimerTask {

		@Override
		public void run() {
			System.out.println("timer executask");

			if (doeScreenshotTask) {
				doeScreenshotTask = false;
				System.out.println("doeScreenshotTask");

				wv = (WebView) findViewById(R.id.wv);

				// wanneer je een link aanklikt, niet de browser van android
				// openen maar in de huidige webview
				wv.setWebViewClient(new WebViewClientExtended());

				wv.getSettings().setJavaScriptEnabled(true);

				wv.loadUrl(url);

				// timer
				t = new Timer(true);

				int del = (delay) * 1000;
				int inter = (interval) * 1000;
				int co = count;

				t.scheduleAtFixedRate(new ScreenshotTimerTask(co), del, inter);
			}
		}
	}

	public void browserScreenshot(Task app, Task task) {
		screenshotTask = task;
		appTask = app;
		delay = Integer.parseInt(task.getParameterValue("delay"));
		interval = Integer.parseInt(task.getParameterValue("interval"));
		count = Integer.parseInt(task.getParameterValue("count"));
		url = app.getParameterValue("parameter");

		doeScreenshotTask = true;

	}

	/* Creates the menu items */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, STOP, 0, "Stop");
		return true;
	}

	/* Handles item selections */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case STOP:
			// android methode
			finish();
			return true;
		}
		return false;
	}

	/* when a link is clicked, it will open in the webview and not in de browser */
	private class WebViewClientExtended extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			setTitle(url);
			System.out.println("page finished");
		}
	}

	private class ScreenshotTimerTask extends TimerTask {

		private int count = 0;
		private int countmax = 0;

		public ScreenshotTimerTask(int i) {
			super();
			countmax = i;
		}

		@Override
		public void run() {
			System.out.println("timer uitgevoerd");
			wv = (WebView) findViewById(R.id.wv);
			View v1 = wv.getRootView();
			v1.setDrawingCacheEnabled(true);
			Bitmap bm = v1.getDrawingCache();
			if (bm != null) {
				savepicture(bm);
			}
		}

		private void savepicture(Bitmap bm) {

			FileOutputStream fOut;

			try {
				System.out.println(count);

				fOut = openFileOutput("nr" + count + ".png",
						Context.MODE_WORLD_WRITEABLE);

				bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
				aantImages = count;

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

			count++;
			System.out.println("count: " + count);
			if (count == countmax) {
				t.cancel();
				System.out.println("Screenshots nemen is gedaan");
				send();
				cd.onFinished(appTask);
				cd.onFinished(screenshotTask);

			}
		}

		private void send() {
			try {
				for (int i = 0; i <= aantImages; i++) {
					System.out.println(count);
					FileInputStream In = openFileInput("nr" + i + ".png");
					Bitmap b = BitmapFactory.decodeStream(In);

					ByteArrayOutputStream os = new ByteArrayOutputStream();
					b.compress(Bitmap.CompressFormat.JPEG, 100, os);

					byte[] array = os.toByteArray();
					deleteFile("nr" + i + ".png");
					cd.sendImage(array, screenshotTask.getTaskId());
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}